package org.xhy.hrm.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.xhy.hrm.asserts.GlobleAssert;
import org.xhy.hrm.domain.LoginUser;
import org.xhy.hrm.mapper.LoginUserMapper;
import org.xhy.hrm.service.ILoginUserService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.xhy.hrm.util.HttpUtil;

import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xhy
 * @since 2021-09-11
 */
@Service
public class LoginUserServiceImpl extends ServiceImpl<LoginUserMapper, LoginUser> implements ILoginUserService {

    private String URL_TOKEN = "http://localhost:4020/oauth/token?client_id=%s&client_secret=%s&grant_type=password&username=%s&password=%s";

    @Autowired
    private LoginUserMapper loginUserMapper;

    @Override
    public Map<String, String> login(LoginUser loginUser) {
        //校验参数
        String username = loginUser.getUsername();
        String password = loginUser.getPassword();
        GlobleAssert.hasText(username,"用户名不能为空");
        GlobleAssert.hasText(password,"密码不能为空");

        //通过用户名查询
        LoginUser user = loginUserMapper.selectByName(username);
        GlobleAssert.isNotNull(user,"账号不存在！");

        //拼接url
        String clientId = user.getClientId();
        String clientSecret = user.getClientSecret();

        String format = String.format(URL_TOKEN, clientId, clientSecret, username, password);

        //工具类发送请求
        Map<String, String> stringStringMap = HttpUtil.sendPost(format);

        return stringStringMap;
    }
}
